# -*- coding: utf-8 -*-
import hashlib
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://api.jlfwx.com/pay.aspx'

APP_CONF = {
    '2412': {
        'API_KEY': '1a90346f14b2458bac0d7f4e353863cc'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def gen_sign1(d, key):
    s = 'userid={}&orderid={}&bankid={}&keyvalue={}'.format(d['userid'], d['orderid'], d['bankid'], key).lower()
    return generate_sign(s)


def gen_sign2(d, key):
    s = 'money={}&userid={}&orderid={}&bankid={}&keyvalue={}'.format(d['money'], d['userid'], d['orderid'], d['bankid'],
                                                                     key).lower()
    return generate_sign(s)


def gen_notify_sign1(d, key):
    s = 'returncode={}&userid={}&orderid={}&keyvalue={}'.format(d['returncode'], d['userid'], d['orderid'], key).lower()
    return generate_sign(s)


def gen_notify_sign2(d, key):
    s = 'money={}&returncode={}&userid={}&orderid={}&keyvalue={}'.format(d['money'], d['returncode'], d['userid'],
                                                                         d['orderid'], key).lower()
    return generate_sign(s)


def gen_query_sign(d, key):
    s = 'userid={}&orderid={}&keyvalue={}'.format(d['userid'], d['orderid'], key).lower()
    return generate_sign(s)


def verify_notify_sign(params, key):
    calculated_sign1 = gen_notify_sign1(params, key)
    calculated_sign2 = gen_notify_sign2(params, key)
    if params['sign'] != calculated_sign1 or params['sign2'] != calculated_sign2:
        _LOGGER.info("yhxpay sign: %s, calculated sign: %s", params['sign'], calculated_sign1)
        _LOGGER.info("yhxpay sign: %s, calculated sign2: %s", params['sign2'], calculated_sign2)
        raise ParamError('sign not pass, data: %s' % params)


def build_form(params):
    html = u"<head><title>loading...</title></head><form id='yhxpaysubmit' name='yhxpaysubmit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['yhxpaysubmit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']  # wechat or alipay
    pay_type = '2005' if service == 'wxpay' else '2009'
    app_id = info['app_id']
    api_key = _get_api_key(app_id)

    p_dict = OrderedDict((
        ('userid', app_id),
        ('orderid', str(pay.id)),
        ('money', str(pay_amount)),
        ('url', '{}/pay/api/{}/yhxpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('bankid', pay_type),
        ('ext', 'zxczcxcz'),
    ))
    p_dict['sign'] = gen_sign1(p_dict, api_key)
    p_dict['sign2'] = gen_sign2(p_dict, api_key)
    _LOGGER.info('yhxpay before data: %s', p_dict)
    html_text = build_form(p_dict)
    cache_id = redis_cache.save_html(pay.id, html_text)
    charge_resp = {
        'charge_info': settings.PAY_CACHE_URL + cache_id,
    }
    return charge_resp


def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("yhxpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('yhxpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = data['returncode']
    trade_no = ''
    total_fee = float(data['money'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('yhxpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)

    async_job.notify_mch(pay_id)


_QUERY_GATEWAY = 'http://api.jlfwx.com/query.aspx?userid={}&orderid={}&sign={}'


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    p_dict = OrderedDict((
        ('orderid', pay_order.id),
        ('userid', app_id),
    ))
    p_dict['sign'] = gen_query_sign(p_dict, api_key)
    get_url = _QUERY_GATEWAY.format(p_dict['userid'], p_dict['orderid'], p_dict['sign'])
    response = requests.get(get_url)
    _LOGGER.info('yhxpay query, %s', response.text)
    if response.status_code == 200:
        mch_id = pay_order.mch_id
        trade_status = _get_str(response.text, 'returncode=', '&')
        total_fee = float(_get_str(response.text, 'paymoney=', '&'))
        trade_no = pay_order.id

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee
        }

        if trade_status == '1' and total_fee > 0:
            _LOGGER.info('yhxpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)


if __name__ == '__main__':
    p_dict = OrderedDict((
        ('orderid', '1625018752706810880'),
        ('userid', '2412'),
    ))
    p_dict['sign'] = gen_query_sign(p_dict, '1a90346f14b2458bac0d7f4e353863cc')
    get_url = _QUERY_GATEWAY.format(p_dict['userid'], p_dict['orderid'], p_dict['sign'])
    response = requests.get(get_url)
    print response.text
